# -*- coding: utf-8 -*-
def norm(ZFCdata, FCdata):
    norm_max=max(max(ZFCdata), max(FCdata))
    norm_min=min(min(ZFCdata), min(FCdata))
    ZFCnorm = (ZFCdata-norm_min)/(norm_max-norm_min)
    FCnorm = (FCdata-norm_min)/(norm_max-norm_min)
    return ZFCnorm, FCnorm

def fit_zfc_fc_ka_size_mag(x0 , templist, ZFCdata, FCdata, N, theta, phi, field):
    # fit the ZFCFC with Ka and size distribution
    ka, mu, sigma, magnetisation = x0
    if sigma < 0: sigma = 1e-5
    if mu < 0: mu = 1e-5
    def generate_lognorm(n=None):
        '''generate the volume distribution for a spherical particle with log-normal dist.
        Not the average and variance of the log-normal distribution is NOT the mu and sigma factor here.
        One should calculate the value again.
        
        Use the same hack as the above function, in order to reduce numeric error
        '''
        #mu = 2.58041
        #sigma = 0.121255
        #global mu
        #global sigma
        m = n/2
        dia = random.lognormal(mu,sigma,m)*1e-9
        volume = pi*dia**3/6
        volume = concatenate((volume, volume))
        return volume
    
    FitNP = SWNPs(N, theta, phi, generate_lognorm, ka, 0, magnetisation, 0.00001)
    templist.sort()
    ZFCfit, FCfit = simulate_zfc_fc(FitNP, field, templist)
    norm_up = max(max(FCfit), max(ZFCfit))
    norm_down = min(min(FCfit), min(ZFCfit))
    ZFCfit = (ZFCfit-norm_down)/(norm_up-norm_down)
    FCfit = (FCfit-norm_down)/(norm_up-norm_down)
    #ZFCfit = ZFCfit/norm_up
    #FCfit = FCfit/norm_up
    err = concatenate((ZFCdata-ZFCfit, FCdata-FCfit))
    print 'use ka=%f mu=%f sigma=%f magnetisation=%f estimate error is: %f' %(ka,mu,sigma,magnetisation,(err**2).sum())
    return err
